package org.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 向request域中共享数据
 */
@Controller
public class ScopeController {
    /**
     * 使用ServletApi像request域对象共享数据
     */
    @RequestMapping("/testServletApi")
    public String test(HttpServletRequest request) {
        request.setAttribute("username", "foobar");
        System.out.println(request.getAttribute("username"));
        // request.removeAttribute("username");
        return "success";
    }

    /**
     * 使用ModelAndView向request域对象共享数据
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("username", "zhangsan");
        mav.setViewName("success");
        return mav;
    }

    /**
     * 使用Model向request域对象共享数据
     */
    @RequestMapping("/testModel")
    public String testModel(Model model) {
        model.addAttribute("username", "lisi");
        return "success";
    }

    /**
     * 使用Map向request域对象共享数据
     */
    @RequestMapping("/testMap")
    public String testMap(Map<String, Object> map) {
        map.put("username", "wangwu");
        return "success";
    }

    /**
     * 使用ModelMap向request域对象共享数据
     */
    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap) {
        modelMap.addAttribute("username", "zhaoliu");
        return "success";
    }
}
